package com.guigu.tms.security.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.guigu.tms.commons.order.entity.vo.Result;
import com.guigu.tms.security.service.IValidateCodeService;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class ValidateCodeServiceImpl implements IValidateCodeService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Map<String, Object> create() {
        String key= IdUtil.getSnowflake().nextIdStr();
        Captcha captcha = new ArithmeticCaptcha(115, 42);
        //获取结果
        String value = captcha.text();

        //放入redis缓存,设置过期时间未1分钟
        redisTemplate.opsForValue().set(key,value,Duration.ofMinutes(1));

        Map<String, Object> imgResult = new HashMap<String, Object>(2) {{
            put("img", captcha.toBase64());
            put("key", key);
        }};

        return imgResult;
    }

    @Override
    public Integer check(String key, String value) {
        Integer result=0;
        if(!redisTemplate.hasKey(key)){
            return -1;
        }
        //从redis缓存中查询
        String value1 = redisTemplate.opsForValue().get(key);
        //判断value是否相等
        if(value1.equals(value)){
            result=1;
            redisTemplate.delete(key);
        }
        return result;
    }
}
